﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Outfit : MonoBehaviour
{
    // 记录当前 Outfit 绑定的骨骼对象
    private List<GameObject> bones = new List<GameObject>();

    /// <summary>
    /// 当 Outfit 被销毁时，释放所有绑定的骨骼
    /// </summary>
    private void OnDestroy()
    {
        for (int i = 0; i < bones.Count; i++)
        {
            Outfit.ReleaseBone(bones[i]);
        }
    }

    /// <summary>
    /// 添加骨骼对象，并增加其引用计数
    /// </summary>
    /// <param name="g2">要添加的骨骼 GameObject</param>
    public void Add(GameObject g2)
    {
        bones.Add(g2);
        Outfit.AddBone(g2);
    }

    /**
     * ====================  静态方法  ====================
     */

    // 记录骨骼对象的引用计数
    private static Dictionary<GameObject, int> nodeCounter = new Dictionary<GameObject, int>();

    /// <summary>
    /// 判断某个 GameObject 是否在引用计数字典中
    /// </summary>
    /// <param name="gameObject">要检查的 GameObject</param>
    /// <returns>是否已存在于 nodeCounter</returns>
    public static bool ContainsKey(GameObject gameObject)
    {
        return nodeCounter.ContainsKey(gameObject);
    }

    /// <summary>
    /// 增加骨骼对象的引用计数
    /// </summary>
    /// <param name="g">要增加计数的 GameObject</param>
    private static void AddBone(GameObject g)
    {
        if (nodeCounter.TryGetValue(g, out int count))
        {
            nodeCounter[g] = count + 1;
        }
        else
        {
            nodeCounter[g] = 1;
        }
    }

    /// <summary>
    /// 释放骨骼对象的引用计数，如果计数为 0，则销毁对象
    /// </summary>
    /// <param name="g1">要释放的骨骼 GameObject</param>
    private static void ReleaseBone(GameObject g1)
    {
        if (nodeCounter.TryGetValue(g1, out int count))
        {
            if (count <= 1)
            {
                nodeCounter.Remove(g1);
                GameObject.Destroy(g1); // 计数为 0 时销毁对象
            }
            else
            {
                nodeCounter[g1] = count - 1;
            }
        }
    }
}
